package logic

import (
	"context"
	"errors"
	"pet/model"

	"pet/petrpc/internal/svc"
	"pet/petrpc/petrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddPetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddPetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddPetLogic {
	return &AddPetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddPetLogic) AddPet(in *petrpc.AddPetRequest) (*petrpc.AddPetResponse, error) {
	// todo: add your logic here and delete this line
	var pet model.Pet
	err := model.DB.Find(&pet).Error
	if err != nil {
		return nil, errors.New("宠物名称重复")
	}
	tx := model.DB.Debug().Begin()
	class := model.Class{
		Name: in.ClassName,
	}
	err = tx.Where("name=?", in.ClassName).FirstOrCreate(&class).Error
	if err != nil {
		tx.Rollback()
		return nil, errors.New("宠物品种添加失败")
	}
	user := model.User{
		Name: in.UserName,
	}
	err = tx.Where("name=?", in.UserName).FirstOrCreate(&user).Error
	if err != nil {
		tx.Rollback()
		return nil, errors.New("宠物领养人添加失败")
	}
	pet = model.Pet{
		Name:    in.Name,
		Gender:  in.Gender,
		Info:    in.Info,
		ClassId: int(class.ID),
		UserId:  int(user.ID),
	}
	err = tx.Create(&pet).Error
	if err != nil {
		tx.Rollback()
		return nil, errors.New("宠物领养信息登记失败")
	}
	tx.Commit()
	return &petrpc.AddPetResponse{
		PetId: int64(pet.ID),
	}, nil
}
